package main

import (
	"encoding/json"
	"fmt"
	"io"
	"api_report/cronjob"
	"api_report/logconf"
	"api_report/readcf"
	"net/http"
	"strconv"
	"strings"
	"time"
)

var (
	content = readcf.GetParm() // 读取配置文件
	logger  = logconf.LogFormat(content.LogPath)
)

type RequestFormat struct {
	RemoteAddr string `json:"remote_addr"`
	RequestUri string `json:"request_uri"`
	Duration   string `json:"duration"`
}

func IndexHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "error: %d", http.StatusNotFound) // 直接访问根路径返回404
}

func WsDebugHandlerDirect(w http.ResponseWriter, r *http.Request) {
	router := strings.Split(r.RequestURI, "/")
	host := content.ServerList[router[3]].Host // 主机地址
	if host == "" {
		fmt.Fprintf(w, "no such host: %v", router[3])
		return
	}
	tag := content.ServerList[router[3]].Tag // 服务角色
	client := &http.Client{Timeout: 2 * time.Second}
	resp, err := client.Get(host + "/debug/pprof/goroutine?debug=1")
	if err != nil {
		logger.Error(err)
		fmt.Fprintf(w, "%v", err)
		return
	}
	defer resp.Body.Close()
	Byte, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Fprintf(w, "read err: %s", err)
	} else {
		fmt.Fprintf(w, "%s\n\n%s", tag, Byte)
	}
}

func CountTime(next http.Handler) http.Handler {
	return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
		Begin := time.Now()
		next.ServeHTTP(rw, r)
		TimeElapsed := time.Since(Begin).Milliseconds()
		LogFormat := &RequestFormat{
			RemoteAddr: r.RemoteAddr,
			RequestUri: r.RequestURI,
			Duration:   strconv.Itoa(int(TimeElapsed)) + "ms",
		}
		response, err := json.Marshal(LogFormat)
		if err != nil {
			logger.Error(err)
		} else {
			logger.Info(string(response))
		}

	})
}

func main() {
	cronjob.GetPngCronJob(content, content.LogPath) // 导入计划任务
	http.HandleFunc("/", IndexHandler)
	http.Handle("/apiserver/pprof/", CountTime(http.HandlerFunc(WsDebugHandlerDirect)))
	err := http.ListenAndServe(":9596", nil)
	if err != nil {
		panic(err)
	}
}
